<?php

namespace app\frontend\controller;

use app\admin\model\Caser;
use think\Controller;
use think\Db;


class Cases extends Controller
{
    public function index()
    {

        $environments = Db::query('SELECT count(*) as c, environment FROM d_casies GROUP BY environment ORDER BY c DESC LIMIT 5');
        $industries = Db::query('SELECT count(*) as c, industry FROM d_casies GROUP BY industry ORDER BY c DESC LIMIT 5');
        $varieties = Db::query('SELECT count(*) as c, variety FROM d_casies GROUP BY variety ORDER BY c DESC LIMIT 5');
        $dates = Db::query('SELECT count(*) as c, date FROM d_casies GROUP BY date ORDER BY c DESC LIMIT 5');

        $case = new Caser();
        $casies = $case->table('d_casies');
        $title = input('title');
        if (isset($title)) {
            $casies->where('title', 'like', "%{$title}%");
        }

        $date = input('date');
        if ($date != '') {
            $casies->where('date', substr($date, 0, 4));
        }
        $environment = input('environment');
        if ($environment != '') {
            $casies->where('environment', $environment );
        }
        $industry = input('industry');
        if ($industry  != '') {
            $casies->where('industry', $industry );
        }
        $variety = input('variety');
        if ($variety != '') {
            $casies->where('variety', $variety );
        }

        $cases = $casies->paginate(9);

        $this->assign('cases', $cases);
        $this->assign('environments', $environments);
        $this->assign('industries', $industries);
        $this->assign('varieties', $varieties);
        $this->assign('dates', $dates);

        echo $this->fetch();
    }

    public function details()
    {
        $id = input('id');

        $cases = Db::table('d_casies')->field('id,imagies,title')->select();
        $case = Db::table('d_casies')->where('id',$id)->find();
        shuffle($cases);

        $case['mul_image'] = json_decode($case['mul_image'], true) ;
        $case['mul_image'] = $case['mul_image'] == null ? [] : $case['mul_image'];
        $this->assign('case', $case);
        $this->assign('cases', array_slice($cases, 0, 4));
        echo $this->fetch();
    }
}
